<template>
  <div class="bg-box">
    <div class="left">
      <img src="../../assets/images/icon-128.png" class="logo-img" alt="" />
      <p>{{ "收藏云书签系统" }}</p>
    </div>
    <div class="right">
      <div class="login-box" v-if="!isReg">
        <span v-if="isReg" class="backtoLogin" @click="isReg = false"
          ><el-icon><back /></el-icon
        ></span>
        <h1 class="welcomeToLogin">{{ isReg ? "注册账号" : "欢迎登录" }}</h1>
        <el-form
          class="form-box"
          ref="logForm"
          :model="form"
          :rules="formRules"
        >
          <el-form-item prop="username">
            <el-input
              v-model="form.username"
              type="text"
              class="login-input-size login-input-background"
              autocomplete="no"
              placeholder="请输入用户名"
            >
              <template #prefix>
                <el-icon><User /></el-icon
                ><span class="input-division-line"></span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="form.password"
              class="login-input-size login-input-background"
              autocomplete="new-password"
              show-password
              placeholder="请输入密码"
            >
              <template #prefix>
                <el-icon><Lock /></el-icon
                ><span class="input-division-line"></span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="verifycode">
            <el-input
              v-model="form.verifycode"
              class="login-input-size code-size login-input-background"
              placeholder="验证码"
            >
              <template #prefix>
                <el-icon><DocumentChecked /></el-icon
                ><span class="input-division-line"></span>
              </template>
            </el-input>
            <p
              id="captcha"
              @click="getVerifyCode"
              style="margin-left: 30px; cursor: pointer"
            >
              {{ verifycode }}
            </p>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="loading"
              @click="handleBtnClick"
              class="wbtn"
              >立即登录
            </el-button>
          </el-form-item>
          <el-form-item label="">
            <div class="foot">
              <el-link
                class="font-size ml-5 link-background"
                type="primary"
                @click="registerFn"
                :underline="false"
              >
                立即注册
              </el-link>
              <el-link
                class="font-size ml-4 link-background"
                :href="installFn()"
                type="primary"
                :underline="false"
                style="margin-left: 10px"
              >
                插件下载
              </el-link>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="login-box" v-else>
        <span class="backtoLogin" @click="isReg = false"
          ><el-icon><back /></el-icon
        ></span>
        <h1 class="welcomeToLogin">注册账号</h1>
        <el-form
          class="form-box"
          ref="regFormRef"
          :model="regForm"
          :rules="formRules"
        >
          <el-form-item prop="username">
            <el-input
              v-model="regForm.username"
              type="text"
              class="login-input-size login-input-background"
              autocomplete="no"
              placeholder="请输入用户名"
            >
              <template #prefix>
                <el-icon><User /></el-icon>
                <span class="input-division-line"></span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input
              v-model="regForm.email"
              type="text"
              class="login-input-size login-input-background"
              autocomplete="no"
              placeholder="请输入邮箱"
            >
              <template #prefix>
                <el-icon><Message /></el-icon>
                <span class="input-division-line"></span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="regForm.password"
              class="login-input-size login-input-background"
              autocomplete="new-password"
              show-password
              placeholder="请输入密码"
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
                <span class="input-division-line"></span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="confirmPwd">
            <el-input
              v-model="regForm.confirmPwd"
              show-password
              class="login-input-size login-input-background"
              placeholder="请确认密码"
            >
              <template #prefix>
                <el-icon><CircleCheck /></el-icon>
                <span class="input-division-line"></span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="loading"
              @click="handleBtnClick"
              class="wbtn"
              >立即注册
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useUserStore } from "~/utils/pinia/user.js";
import { mAxios } from "~/utils/axios/axios.js";
const verifycode = ref("");
let $router = useRouter();
let loading = ref(false);
const userStore = useUserStore();
const logForm = ref();
const regFormRef = ref();
const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== regForm.password) {
    callback(new Error("两次输入的密码不一致！"));
  } else {
    callback();
  }
};
const formRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 16, message: "长度在 3 到 16 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 3, max: 24, message: "长度在 3 到 25 个字符", trigger: "blur" },
  ],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  verifycode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 4, message: "长度为 4 个字符", trigger: "blur" },
  ],
  confirmPwd: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { validator: validatePass2, trigger: "blur" },
  ],
};
const form = reactive({
  username: "yangxz",
  password: "het@1234",
  verifycode: "dddd",
});
const regForm = reactive({
  username: "",
  email: "",
  password: "",
  confirmPwd: "",
});

const isReg = ref(false);
const handleBtnClick = async () => {
  if (isReg.value) {
    await regFormRef.value.validate((valid) => {
      if (valid) {
        loading.value = true;
        const params = {
          username: regForm.username,
          nickname: regForm.username,
          email: regForm.email,
          password: regForm.password,
        };
        mAxios
          .post("auth/register", params)
          .then((res) => {
            loading.value = false;
            if (res.data.succeed) {
              ElMessage.success("注册成功");
              isReg.value = false;
            } else {
              ElMessage.error(res.data.message);
            }
          })
          .catch((error) => {
            loading.value = false;
          });
      }
    });
  } else {
    await logForm.value.validate((valid) => {
      if (valid) {
        if (form.verifycode != verifycode.value.toLowerCase()) {
          ElMessage.error("验证码验证失败，请重试");
          form.verifycode = ""
          getVerifyCode()
          return;
        }
        loading.value = true;
        const info = {
          username: form.username,
          password: form.password,
        };
        mAxios
          .post("auth/login", info)
          .then((res) => {
            loading.value = false;
            if (res.data.succeed) {
              ElMessage.success("登录成功");
              for (let k in res.data.data) {
                sessionStorage.setItem(k, res.data.data[k]);
              }
              $router.push({ path: "/home" });
            } else {
              ElMessage.error(res.data.message);
              getVerifyCode();
            }
          })
          .catch((error) => {
            loading.value = false;
          });
      }
    });
  }
};

// 前往注册
const registerFn = () => {
  isReg.value = true;
  regFormRef.value.resetFields()
};

// 插件下载函数
const installFn = (type) => {
  // return (
  //   window.location.protocol +
  //   "//" +
  //   window.location.host +
  //   URI +
  //   "versionManager/package/install?os=" +
  //   type
  // );
};

const getVerifyCode = () => {
  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let captcha = "";
  for (let i = 0; i < 4; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    captcha += characters.charAt(randomIndex);
  }
  verifycode.value = captcha;
};
onMounted(() => {
  getVerifyCode();
});
</script>

<style lang="scss" scoped>
.bg-box {
  display: flex;
  justify-content: center;
  background: url(../../assets/images/login-background.jpg) no-repeat center
    center / cover fixed;
}
.foot {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

.left,
.right {
  width: 50%;
}

.left {
  position: absolute;
  top: 54px;
  left: 62px;
  display: flex;
  align-items: center;

  .logo-img {
    display: inline-block;
    height: 44px;
  }

  p {
    display: inline-block;
    font-size: 22px;
    font-weight: 400;
    margin-left: 20px;
  }
}

.login-box {
  position: fixed;
  right: 16.67%;
  top: 22.96%;
  width: 416px;
  height: 480px;
  border-radius: 12px;
  background: #ffffff;
  box-shadow: 0 2px 15px 0 rgba(120, 78, 78, 0.3);
}

.form-box {
  width: 330px;
  margin: 0 auto;
}

.welcomeToLogin {
  font-weight: bold;
  font-size: 27px;
  color: #02112b;
  font-style: normal;
  text-transform: none;
  margin: 50px 0;
  text-align: center;
}

.login-input-size,
.code-size {
  width: 100%;
  height: 45px;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.45);

  :deep(.el-input__wrapper) {
    background-color: rgba(0, 0, 0, 0.03);
    border-radius: 8px;
    box-shadow: none;
    .el-input__inner {
      color: #000;
    }
  }
}
.code-size {
  width: 200px;
}

.code-img {
  width: 116px;
  height: 43px;
  margin-left: 12px;
  line-height: 20px;
  :deep(.el-image__inner) {
    border-radius: 8px;
  }
}
.link-background {
  // color: #973397;
}
:deep(.form-box .el-input__prefix) {
  // color: #6c216d;
  font-size: 24px;
}

.input-division-line {
  display: inline-block;
  width: 1px;
  height: 26px;
  background-color: rgba(0, 0, 0, 0.45);
  margin-left: 12px;
}

.input-img {
  width: 18px;
  height: 18px;
}

.login-color {
  color: #fff;
  background-color: #973397 !important;
  border-radius: 8px !important;
}
.backtoLogin {
  position: absolute;
  top: 53px;
  left: 43px;
  font-size: 20px;
  cursor: pointer;
}
.wbtn {
  width: 100%;
  padding: 20px 0;
}
</style>
